/**
 * 
 */
package vanhoc.android.mediakool;
import java.io.File;
import java.util.ArrayList;

import vanhoc.android.mediakool.R;
import vanhoc.android.mediakool.custom.adapter.DialogPlaylistAdapter;
import vanhoc.android.mediakool.custom.adapter.SongListAdapter;
import vanhoc.android.mediakool.db.DatabaseHelper;
import vanhoc.android.medialcool.helper.AlertDialogManager;
import vanhoc.android.medialcool.item.data.PlaylistItemData;
import vanhoc.android.medialcool.item.data.SongItemData;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

/**
 * @author Administrator
 * Hien thi nhung bai hat thuoc 1 album hoac cua 1 artist nao do (dung chung cho viec chon xem danh sach song cua 1 album hay 1 artist)
 */
public class SongsActivity extends Activity implements OnItemClickListener,OnItemLongClickListener {
	ArrayList<SongItemData> arrListSong;
	
	//id bai hat dang hat, mac dinh chua co bai hat nao hat thi gan  = 0
	int songPlayingID;
		
	//Bien luu gia tri cho biet co nghe toan bo danh sach nhac hay khong
	Boolean isPlayAll = false;
	
	//Bien luu gia tri co biet co xao tron  list nhac hay khong
	Boolean isShuffle = false;
	
	//Bien luu ten field chua ds song can lay (vd: muon lay ve ds song cua album hoac genre hoac playlist ..._
	private String fieldName;
	
	//bien luu gia tri cua field can lay ve ds song ( vd: can lay ve ds song cua album(fieldname) co ten la mp3.zing.vn (fieldValue) )
	private String fieldValue;
	
	
	//Bien luu id cua playlist dc chon de mo ds  nhac cua playlist do ( neu user chon tab playlist)
	private int playlist_id;
	
	/**
	 * Dialog alert option for a song
	 */
	Dialog featureDialog;
	
	Dialog dialogPlaylist;
	
	/**
	 * danh sach cac playlist (khi user chon menu\add to playlist
	 */
	ArrayList<PlaylistItemData> arrPlaylist;
	
	
	ListView lvPlaylist;
	
	
	int songSelectedID;
	
	String songSelectedTitle;
	
	AlertDialogManager alertDialog = new AlertDialogManager();
	
	private DatabaseHelper databaseHelper	=	new DatabaseHelper(this);
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.song);
		
		//lay ve du lieu truyen tu cac activity kia thong qua intent
		getIntentData();
		
		//khoi  tao listview song
		initListSong();
	}
	
	
	private void getIntentData() {
		//Khi dang choi nhac o min hinh MusicPlayerActivity, user back lai man hinh TabControlActivity se gui qua Intent id cua bai hat dang choi
		//Con khi moi mo ung dung len(tuc la chua choi nha) thi khong co Intent
		//lay ve id cua bai hat dang choi quan intent (neu co)
		this.songPlayingID	=	 getIntent().getExtras().getInt("songPlayingID");
		
		//Lay ve Key va value cua ben AlbumActivity , GenreActivity ... gui qua
		this.fieldName 	= getIntent().getExtras().getString("FIELDNAME");
		this.fieldValue = getIntent().getExtras().getString("FIELDVALUE");
		
		//lay ve id cua playlist trong t/h user click o tab playlist
		playlist_id	=	getIntent().getExtras().getInt("PLAYLIST_ID");
	}


	private void initListSong() {
		ListView listViewSong	=	(ListView) findViewById(R.id.listSong);
		
		//lay ve list nhac theo du lieu tuong ung ma  intent truyen vao (vd: list cua 1 album, haycua 1 artist or 1 playlist or 1 genre
		this.arrListSong	=	this.getListSong();
		
		//init Adapter
		SongListAdapter songListAdapter = new SongListAdapter(getApplicationContext(), R.id.listSong, arrListSong);
		
		//gui id cua bai hat dang hat sang Adapter de khi hien thi list song len listview, thi bai hat dang hat dc thay bang 1 icon khac
		if (this.songPlayingID != 0) songListAdapter.setSongPlayingID(this.songPlayingID);
		
		//Set Adapter cho listview
		listViewSong.setAdapter(songListAdapter);
		
	
		//set onClick
		listViewSong.setOnItemClickListener(this);
		listViewSong.setOnItemLongClickListener(this);
		
		songListAdapter.notifyDataSetChanged();
	}
	
	/**
	 * Lay ve danh sach bai hat theo fieldName
	 * @return
	 */
	public ArrayList<SongItemData> getListSong(){
		ArrayList<SongItemData> listSong = new ArrayList<SongItemData>();
		
		databaseHelper.openToRead();
		//neu user click o tab artist or genre or album thi se lay ve ds nhac theo album or artist or genre do
		if (this.fieldName!=null && this.fieldValue!=null) {
			listSong = databaseHelper.getSongListByTagName(fieldName,fieldValue);
		}
		
		if (this.playlist_id > 0) {
			Cursor cursor = databaseHelper.getListSongByPlaylist(playlist_id);
			cursor.moveToFirst();
			for (int i = 0; i < cursor.getCount(); i++) {
				SongItemData item = new SongItemData();
				item.setID(Integer.parseInt(cursor.getString(0)));
				item.setName(cursor.getString(1));
				item.setAlbum(cursor.getString(2));
				item.setArtist(cursor.getString(3));
				item.setGenre(cursor.getString(4));
				item.setDuration(cursor.getString(5));
				item.setPath(cursor.getString(6));
				
				listSong.add(item);
				cursor.moveToNext();
			}
		}
    	databaseHelper.close();
    	
    	return listSong;
	}


	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater menuInflater = getMenuInflater();
    	menuInflater.inflate(R.menu.all_song_menu, menu);
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
    		case R.id.play_all_menu: //phat di tin hieu la choi tat ca bai hat trong list va lau dau tien la choi bai dau tien
    			isPlayAll = true;
    			Intent intent = new Intent(SongsActivity.this, MusicPlayerActivity.class);
    			
    			intent.putExtra("PLAYALL_FEATURE", isPlayAll);

    			//put key : tuc la ten field trogn song table (de biet dc lay ds bai hat cua 1 genre, hay 1 album, hay 1 playlist nao)
    			intent.putExtra("FIELDNAME", this.fieldName);
    			
    			//put value : tuc la ten field can lay ( vidu lay ds bai hat cua Genre co title la POP)
    			intent.putExtra("FIELDVALUE", this.fieldValue);

    			//put playlist id (neu co)
    			intent.putExtra("PLAYLIST_ID", this.playlist_id);
    			
    			startActivity(intent);
    			return true;
    		case R.id.shuffle_menu : //trong danh sach va phat bai dau tien trong danh sach da trong do
    			isShuffle = true;
    			Intent it = new Intent(SongsActivity.this, MusicPlayerActivity.class);
    			
    			it.putExtra("SHUFFLE_FEATURE", isShuffle);

    			//put key : tuc la ten field trogn song table (de biet dc lay ds bai hat cua 1 genre, hay 1 album, hay 1 playlist nao)
    			it.putExtra("FIELDNAME", this.fieldName);
    			
    			//put value : tuc la ten field can lay ( vidu lay ds bai hat cua Genre co title la POP)
    			it.putExtra("FIELDVALUE", this.fieldValue);
    			
    			//put playlist id (neu co)
    			it.putExtra("PLAYLIST_ID", this.playlist_id);
    			
    			startActivity(it);
    			return true;
			default:
				return super.onOptionsItemSelected(item);
		}
    }


    @Override
	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
		int songID = arrListSong.get(position).getID();
		
		//choi bai hat da dc chon
		playSong(songID);
	}

    
    
	private void playSong(int songID) {
		Intent intent = new Intent(SongsActivity.this, MusicPlayerActivity.class);
		
		//put key : tuc la ten field trogn song table (de biet dc lay ds bai hat cua 1 genre, hay 1 album, hay 1 playlist nao)
		intent.putExtra("FIELDNAME", this.fieldName);
		
		//put value : tuc la ten field can lay ( vidu lay ds bai hat cua Genre co title la POP)
		intent.putExtra("FIELDVALUE", this.fieldValue);
		
		//put playlist id (neu co)
		intent.putExtra("PLAYLIST_ID", this.playlist_id);
		
		intent.putExtra("songID", songID);
		
		startActivity(intent);
	}


	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
		songSelectedID = arrListSong.get(position).getID();
		songSelectedTitle = arrListSong.get(position).getName();
		
		//hien thi cac tuy chon dang listview 
		showFeatureList();
		
		return false;
	}
    
	private void showFeatureList() {
		featureDialog = new Dialog(SongsActivity.this,0);
		featureDialog.setTitle(songSelectedTitle);
		featureDialog.setContentView(R.layout.listview);
		featureDialog.show();
		
		String[] options;
		//neu Activity nay hien thi ds nhac theo playlist thi co them chuc nang xoa bai nhac khoi playlist
		if (this.playlist_id > 0) {
			options = getResources().getStringArray(R.array.list_feature_for_song_playlist);
		}else{
			options = getResources().getStringArray(R.array.list_feature_for_song);
		}
		
		//list view
		ListView listOption = (ListView) featureDialog.findViewById(R.id.listView);
		
		ArrayAdapter<String>  adapter = new ArrayAdapter<String>(SongsActivity.this, android.R.layout.simple_list_item_1, options);
		listOption.setAdapter(adapter);
		
		listOption.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?>  parent, View v, int position,long id) {
				switch (position) {
					case 0:
						playSong(songSelectedID);
						break;
					case 1:
						addToPlaylist();
						break;
					case 2:
						//set ringstone
						break;
					case 3: //xoa 1 bai hat
						//Neu la bai hat dang hat thi khong xoa dc. Neu khong phai thi xoa dc
						deleteSelectedSong();
						break;
					case 4: //xoa 1 bai hat
						editSongTitle(songSelectedTitle);
						break;
					case 5: //xoa 1 bai hat
						removeFromPlaylist(songSelectedID,playlist_id);
						break;
					default:
						break;
				}			
			}
		});
	}


	/**
	 * Xoa 1 bai hat khoi playlist hien tai
	 * @param songPlayingID2
	 * @param playlist_id2
	 */
	protected void removeFromPlaylist(int sid, int pid) {
		databaseHelper.openToWrite();
		databaseHelper.removeSongFromPlaylist(sid, pid);
		databaseHelper.close();
		Toast.makeText(getApplicationContext(), R.string.successfully, Toast.LENGTH_LONG).show();
		featureDialog.dismiss();
    	initListSong();
	}




	// chinh sua ten bai hat
	protected void editSongTitle(String songTitle) {
		final Dialog dialogEditSongTitle = new Dialog(SongsActivity.this, 0);
		dialogEditSongTitle.setTitle(getResources().getString(R.string.edit));
		dialogEditSongTitle.setContentView(R.layout.add_edit_title_layout);
		dialogEditSongTitle.getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		dialogEditSongTitle.show();
		
		//lay ve cac thanh phan cua layout add_playlist_layout thogn qua dialogAddPlaylist
		final EditText inputTitle 			= (EditText) dialogEditSongTitle.findViewById(R.id.txtTitle);
		inputTitle.setText(songSelectedTitle);
		final Button btnSave 				= (Button) dialogEditSongTitle.findViewById(R.id.btnSave);
		Button btnCancel 					= (Button) dialogEditSongTitle.findViewById(R.id.btnCancel);
		
		//set onclickListener for btnSave
		btnSave.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String newSongTitle = inputTitle.getText().toString();
				if (newSongTitle.equals(null) || newSongTitle.equals("")) 
					alertDialog.showAlertDialog(SongsActivity.this, getString(R.string.error),
												getString(R.string.please_enter_song_title), false);
				else{
					updateSongTitle(newSongTitle);
					dialogEditSongTitle.dismiss();
					featureDialog.dismiss();
                	initListSong();
				}
			}
		});
		/*set onclickListener for btnSave*/
		btnCancel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				dialogEditSongTitle.dismiss();
			}
		});
	}
		
	/**
	 * Update new title
	 * @param newSongTitle
	 */
	protected void updateSongTitle(String newSongTitle) {
		databaseHelper.openToWrite();
		databaseHelper.updateSongTitle(songSelectedID,newSongTitle);
		databaseHelper.close();
		
		Toast.makeText(getApplicationContext(), R.string.successfully, Toast.LENGTH_LONG).show();
	}
		
		
	protected void deleteSelectedSong() {
		//kiem tra xem id cua bai hat dang hat co phai la bai hat da chon de xoa hay ko?Neu khong thi cho xoa. Neu dung thi khong cho xoa
		if (this.songSelectedID == this.songPlayingID) {
			alertDialog.showAlertDialog(SongsActivity.this, getString(R.string.error),
					getString(R.string.cannot_delete_song), false);
		}else{
			confirmDeleteCurrentSong();
		}
	}


	protected void deleteSong() {
		//xoa trong sdcard
    	deleteSongFromSdcard();
    	
    	//xoa trong csdl
    	deleteSongData();
	}

	
	
	/**
     * Xoa du lieu 1 bai hat trong database
     */
	private void deleteSongData() {
		databaseHelper.openToWrite();
		databaseHelper.deleteSong(songSelectedID);
		databaseHelper.close();
	}
	
	
	
	/**
	 * Xoa file mp3 tu trong sdcard
	 */
	private void deleteSongFromSdcard() {
		//co id cua bai hat da chon, truy van vao csdl de lay ve path cua no
		databaseHelper.openToRead();
		String path = databaseHelper.getSongPath(songSelectedID);
		databaseHelper.close();
		
		File mp3File = new File(path);
		if (mp3File.delete()) {
			Toast.makeText(getApplicationContext(), R.string.successfully, Toast.LENGTH_LONG).show();
		}else{
			Toast.makeText(getApplicationContext(), R.string.unsuccessfully, Toast.LENGTH_LONG).show();
		}
		featureDialog.dismiss();
	}
	
	
	/**
     * Confirm 
     */
    public void confirmDeleteCurrentSong(){
    	AlertDialog alert = new AlertDialog.Builder(SongsActivity.this).create();
		alert.setTitle(getResources().getString(R.string.comfirm_delete_song));
		// Setting OK Button
		alert.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                	deleteSong();
                	featureDialog.dismiss();
                	initListSong();
                }
        });
		
		alert.setButton2("Cancel", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				
			}
		});
		
		alert.show();
    }
    

	/**
	 * Add a song into a playlist
	 * songId : id cua bai hat dc onLongClick
	 */
	protected void addToPlaylist() {
		showDialogPlaylist();
	}

	
	//Hien thi dialog danh sach cac playlist
    private void showDialogPlaylist() {
		dialogPlaylist = new Dialog(SongsActivity.this,0);
		dialogPlaylist.setContentView(R.layout.listview);
		dialogPlaylist.setTitle(getResources().getString(R.string.title_add_to_playlist));
		dialogPlaylist.show();
		
		//list view
		lvPlaylist = (ListView) dialogPlaylist.findViewById(R.id.listView);
		
		//list playlist
		databaseHelper.openToRead();
		this.arrPlaylist = databaseHelper.getAllPlaylist();
    	databaseHelper.close();
		
    	//tao mới
    	this.arrPlaylist.add(new PlaylistItemData(0,getResources().getString(R.string.add_new)));
    	
		//adapter
    	DialogPlaylistAdapter pAdapter = new DialogPlaylistAdapter(getApplicationContext(), R.id.listView, arrPlaylist);
    	
    	lvPlaylist.setAdapter(pAdapter);
    	lvPlaylist.setOnItemClickListener(new OnItemClickListener() {

    		@Override
    		public void onItemClick(AdapterView<?> parent, View v, int position,long id) {
    			//neu chon tao moi
    			if (arrPlaylist.get(position).getPlaylistId() == 0) {
    				createPlaylist();
    				//dialogPlaylist.dismiss();
    			}else{ //nguoc lai them vao 1 playlist nao do da tao truoc do
    				//lay ve cai id cua playlist da chon
    				int pid = arrPlaylist.get(position).getPlaylistId();
    				
    				
    				//kiem tra xem playlist co id la pid da chua bai hat nay (sid chua).Neu chua thi them.Neu co roi thi hien thi 1 cau thong bao
    				databaseHelper.openToRead();
    				ArrayList<Integer> listSongIdByPlaylist = databaseHelper.getSongListIdByPlaylist(pid);
    				databaseHelper.close();
    				
    				if (listSongIdByPlaylist.contains(songSelectedID)){//neu bai hat nay truoc do da dc them vao playlist nay
    					Toast.makeText(getApplicationContext(), R.string.existed_song_playlist, Toast.LENGTH_LONG).show();
    				}else{
    					addSongToPlaylist(songSelectedID, pid);
    					Toast.makeText(getApplicationContext(), R.string.add_success, Toast.LENGTH_LONG).show();
    				}
    				dialogPlaylist.dismiss();
    				featureDialog.dismiss();
    			}
    		}
    	});
	}
    
    public void addSongToPlaylist(int sid, int pid){
		databaseHelper.openToWrite();
		databaseHelper.insertSongToPlaylist(sid, pid);
		databaseHelper.close();
	}
    
    //tao moi 1 playlist
  	protected void createPlaylist() {
  		final Dialog dialogAddPlaylist = new Dialog(SongsActivity.this, 0);
  		dialogAddPlaylist.setTitle(getResources().getString(R.string.add_new_playlist));
  		dialogAddPlaylist.setContentView(R.layout.add_edit_title_layout);
  		dialogAddPlaylist.getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
  		dialogAddPlaylist.show();
  		
  		//lay ve cac thanh phan cua layout add_playlist_layout thogn qua dialogAddPlaylist
  		final EditText txtPlaylistTitle 	= (EditText) dialogAddPlaylist.findViewById(R.id.txtTitle);
  		final Button btnSave 				= (Button) dialogAddPlaylist.findViewById(R.id.btnSave);
  		Button btnCancel 					= (Button) dialogAddPlaylist.findViewById(R.id.btnCancel);
  		
  		//set onclickListener for btnSave
  		btnSave.setOnClickListener(new OnClickListener() {
  			
  			@Override
  			public void onClick(View v) {
  				String playlistTitle = txtPlaylistTitle.getText().toString();
  				if (playlistTitle.equals(null) || playlistTitle.equals("")) 
	  				alertDialog.showAlertDialog(SongsActivity.this, getString(R.string.error),
	  											getString(R.string.please_enter_playlist_title), false);
  				else{
  					//kiem tra xem ten playlist user nhap vao da ton tai hay chua.neu chua moi cho tao
  					if (checkPlaylistTitle(playlistTitle)) // neu co roi
	  					alertDialog.showAlertDialog(SongsActivity.this, getString(R.string.error),
									getString(R.string.existed_playlist_title), false);
  					else// neu chua co
  						addNewPlaylist(playlistTitle);
  						dialogAddPlaylist.dismiss();
  				}
  			}
  		});
  		/*set onclickListener for btnSave*/
  		btnCancel.setOnClickListener(new OnClickListener() {
  			
  			@Override
  			public void onClick(View v) {
  				dialogAddPlaylist.dismiss();
  			}
  		});
  	}

	
	/**
	 * Kiem tra xem 1 playlist title da ton tai trong bang playlists table chua
	 * @return
	 */
	public Boolean checkPlaylistTitle(String pTitle){
		for (int i = 0; i < arrPlaylist.size(); i++) {
			if (arrPlaylist.get(i).getPlaylistTitle().equals(pTitle)) {
				return true;
			}
		}
		
		return false;
	}
	
	
	protected void addNewPlaylist(String playlistTitle) {
		databaseHelper.openToWrite();
		//them 1 playlist moi vao playlist table
		databaseHelper.addPlaylist(playlistTitle);
		databaseHelper.close();
		
		//lay ve id cua playlist vua insert vao trong bang playlist table
		int pid = getNewPlaylistID();
		
		//co playlist id va song id ta insert vo song_playlist table
		addSongToPlaylist(songSelectedID, pid);
		
		Toast.makeText(getApplicationContext(), R.string.add_success, Toast.LENGTH_LONG).show();
		dialogPlaylist.dismiss();
	}
	
	// lay ve id playlist vua tao
	protected int getNewPlaylistID() {
			databaseHelper.openToRead();
			int pid = databaseHelper.getLastPlaylistId();
			databaseHelper.close();
			
			return pid;
	}
}
